// Ternary.java - Alexander Shabarshin (30.10.2008-13.11.2008)
// See http://ternary.info and http://3niti.org

public class Ternary
{

 public static final int N =  -1;
 public static final int O =   0;
 public static final int P =   1;

 public static final int NN =  -4;
 public static final int NO =  -3;
 public static final int NP =  -2;
 public static final int ON =  -1;
 public static final int OO =   0;
 public static final int OP =   1;
 public static final int PN =   2;
 public static final int PO =   3;
 public static final int PP =   4;

 public static final int NNN = -13;
 public static final int NNO = -12;
 public static final int NNP = -11;
 public static final int NON = -10;
 public static final int NOO =  -9;
 public static final int NOP =  -8;
 public static final int NPN =  -7;
 public static final int NPO =  -6;
 public static final int NPP =  -5;
 public static final int ONN =  -4;
 public static final int ONO =  -3;
 public static final int ONP =  -2;
 public static final int OON =  -1;
 public static final int OOO =   0;
 public static final int OOP =   1;
 public static final int OPN =   2;
 public static final int OPO =   3;
 public static final int OPP =   4;
 public static final int PNN =   5;
 public static final int PNO =   6;
 public static final int PNP =   7;
 public static final int PON =   8;
 public static final int POO =   9;
 public static final int POP =  10;
 public static final int PPN =  11;
 public static final int PPO =  12;
 public static final int PPP =  13;

 int value;

 public static int fromTernary(String s)
 {
    int n = 0;
    int k = 1;
    for(int i=s.length()-1;i>=0;i--)
    {
      char c = s.charAt(i);
      if(c!='N'&&c!='O'&&c!='P'&&c!='n'&&c!='o'&&c!='p') return 0;
      if(c=='N') n-=k;
      if(c=='P') n+=k;
      if(c=='n') n-=k;
      if(c=='p') n+=k;
      k *= 3;
    }
    return n;
 }

 public static String toTernary(int num)
 {
    int n,m,k;
    String s = null;
    k = 387420489;
    for(int i=0;i<=18;i++)
    {
      n = num/k;
      num -= n*k;
      m = k/2;
      if(num>+m){n++;num-=k;}
      if(num<-m){n--;num+=k;}
      if(n!=0 && s==null) s="";
      if(n==-1) s+="N";
      if(n==0 && s!=null) s+="O";
      if(n==1) s+="P";
      k /= 3;
    } 
    if(s==null) s="O";
    return s;
 }
 
 public String toString()
 {
    return toTernary(value);
 }

 public String toString(int r)
 {
    String s = toTernary(value);
    while(s.length() < r) s="O"+s;
    return s;
 }

 public void set(int n)
 {
    value = n;
 }

 public int get()
 {
    return value;
 }

 public Ternary()
 {
    set(0);
 }

 public Ternary(int n)
 {
    set(n);
 }

 public Ternary(int l, int m, int h)
 {
    set(l+3*m+9*h);
 }

 public Ternary(String s)
 {
    set(fromTernary(s));
 }

 public Ternary(Ternary t)
 {
    set(t.get());
 }

}
